﻿using CPPEI.ETL.Domain.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.Services
{
    public class DtTableService
    {
        public ListResult<Entities.EDtTableColumn> GetColumns(Guid tableId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDtTableColumn> dtcRep = new EntityRepository<Entities.EDtTableColumn>(dbContext);

                List<Entities.EDtTableColumn> list = dtcRep.GetList(p => p.DtTableId == tableId);

                return new ListResult<Entities.EDtTableColumn>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), list);
            }
        }

        public PagedList<Entities.EDtTable> GetTables(int start, int limit)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);

                List<Entities.EDtTable> list = dtRep.Query().OrderBy(p => p.Name).Take(limit).Skip(start).ToList();
                int total = dtRep.Count();
                return new PagedList<Entities.EDtTable>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), start, limit, total, list);
            }
        }

        /// <summary>
        /// 获取数据表列表（带映射数据源信息）
        /// </summary>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public PagedList<Views.VDtTable2> GetPagedVTables(string filter, int start, int limit)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);

                List<Views.VDtTable2> tables = new List<Views.VDtTable2>();

                if (string.IsNullOrEmpty(filter))
                {
                    List<Entities.EDtTable> list = dtRep.Query().OrderBy(p => p.Name).Skip(start).Take(limit).ToList();
                    for (int index = 0; index < list.Count; index++)
                    {
                        Views.VDtTable2 table = new Views.VDtTable2();
                        table.DataTable = list[index];
                        table.DataSources = StoredProcedureMapping.GetDataSourceListByDataTable(dbContext, list[index].Id);
                        tables.Add(table);
                    }
                    int total = dtRep.Count();
                    return new PagedList<Views.VDtTable2>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), start, limit, total, tables);
                }
                else
                {
                    List<Entities.EDtTable> list = dtRep.Query(p=> p.Name.Contains(filter)).OrderBy(p => p.Name).Skip(start).Take(limit).ToList();
                    for (int index = 0; index < list.Count; index++)
                    {
                        Views.VDtTable2 table = new Views.VDtTable2();
                        table.DataTable = list[index];
                        table.DataSources = StoredProcedureMapping.GetDataSourceListByDataTable(dbContext, list[index].Id);
                        tables.Add(table);
                    }
                    int total = dtRep.Count(p => p.Name.Contains(filter));
                    return new PagedList<Views.VDtTable2>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), start, limit, total, tables);
                }
            }
        }

        public SingleResult<Data.DataTableAndColumns> GetTableAndColumns(Guid dtTableId)
        {
            using(EtlDbContext dbContext = new EtlDbContext())
            {
                Data.DataTableAndColumns data = new Data.DataTableAndColumns();
                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);
                data.DataTable = dtRep.Get(p => p.Id == dtTableId);

                EntityRepository<Entities.EDtTableColumn> dtcRep = new EntityRepository<Entities.EDtTableColumn>(dbContext);
                data .Columns= dtcRep.Query(p => p.DtTableId == dtTableId).OrderBy(p => p.Index).ToList();
                return new SingleResult<Data.DataTableAndColumns>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), data);
            }
        }

        public ServiceResult<Views.VDtTableDetail> GetVTable(Guid dtTableId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                try
                {
                    EntityRepository<Views.VDtSourceDataIdentity> dsdiRep = new EntityRepository<Views.VDtSourceDataIdentity>(dbContext);

                    Views.VDtTableDetail model = new Views.VDtTableDetail();

                    EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);
                    model.DataTable = dtRep.Get(p => p.Id == dtTableId);

                    model.DataSources = new List<Views.VDtTableDetail.DataSourceMapping>();
                    List<Entities.DtSource> sources = StoredProcedureMapping.GetDataSourceListByDataTable(dbContext, dtTableId);
                    for (int index = 0; index < sources.Count; index++)
                    {
                        Views.VDtTableDetail.DataSourceMapping mapping = new Views.VDtTableDetail.DataSourceMapping();
                        mapping.DataSource = sources[index];
                        mapping.Columns = StoredProcedureMapping.GetDtTableColumnAndMapping(dbContext, dtTableId, sources[index].Id);
                        mapping.DataIdentities = dsdiRep.Query(p => p.DtSerId == sources[index].DtSerId && p.DtSourceId == sources[index].Id).OrderBy(p => p.Index).ToList();
                        model.DataSources.Add(mapping);
                    }

                    return new ServiceResult<Views.VDtTableDetail>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), model);
                }
                catch(Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("获取数据表:{0}详细信息出错,ex:{1}", dtTableId, ex));

                    return new ServiceResult<Views.VDtTableDetail>(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        public ServiceResult<Models.MDtTableData> GetData(Guid tableId, int start, int limit, out int total)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);
                Entities.EDtTable eTable = dtRep.Get(p => p.Id == tableId);

                EntityRepository<Entities.EDtTableColumn> dtcRep = new EntityRepository<Entities.EDtTableColumn>(dbContext);

                List<Entities.EDtTableColumn> dtColumns = dtcRep.GetList(p => p.DtTableId == tableId);

                List<string> columns = new List<string>();
                List<string> pks = new List<string>();
                for (int index = 0; index < dtColumns.Count; index++)
                {
                    Entities.EDtTableColumn vDtColumn = dtColumns[index];
                    columns.Add(vDtColumn.Name);

                    if(vDtColumn.PK)
                    {
                        pks.Add(vDtColumn.Name);
                    }
                }

                int tTotal = 0;

                System.Data.DataTable dataTable = null;
                if(eTable.IsRawDt)
                {
                    pks.Add(DEF.DtTableColumns.SYSCOL_Id);

                    dataTable = CPPEI.ETL.Domain.Util.DtTableUtil.GetPagedDataFromRawTable(dbContext,
                        eTable.ActualName,
                        columns,
                        start,
                        limit,
                        out tTotal);
                }
                else
                {
                    dataTable = CPPEI.ETL.Domain.Util.DtTableUtil.GetPagedDataFromTable(dbContext,
                        eTable.ActualName,
                        columns,
                        pks,
                        start,
                        limit,
                        out tTotal);

                }

                total = tTotal;

                Models.MDtTableData mDtTableData = new Models.MDtTableData(start, limit, total, dataTable);
                mDtTableData.PKCloumns.AddRange(pks);
                return new ServiceResult<Models.MDtTableData>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), mDtTableData);
            }
        }

        public ServiceResult<Models.MDtTableData> GetSingleData(Guid tableId, string[] pkColumns, string[] pkValues)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);
                Entities.EDtTable eTable = dtRep.Get(p => p.Id == tableId);
                EntityRepository<Entities.EDtTableColumn> dtcRep = new EntityRepository<Entities.EDtTableColumn>(dbContext);

                List<Entities.EDtTableColumn> dtColumns = dtcRep.GetList(p => p.DtTableId == tableId);

                List<string> columns = new List<string>();
                List<string> pks = new List<string>();
                for (int index = 0; index < dtColumns.Count; index++)
                {
                    Entities.EDtTableColumn vDtColumn = dtColumns[index];
                    columns.Add(vDtColumn.Name);

                    if (vDtColumn.PK)
                    {
                        pks.Add(vDtColumn.Name);
                    }
                }

                System.Data.DataTable dataTable = CPPEI.ETL.Domain.Util.DtTableUtil.GetSingleDataFromTable(dbContext,
                    eTable.ActualName,
                    columns, 
                    pkColumns,
                    pkValues);

                Models.MDtTableData mDtTableData = new Models.MDtTableData(0, 1, 1, dataTable);
                mDtTableData.PKCloumns.AddRange(pks);
                return new ServiceResult<Models.MDtTableData>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), mDtTableData);
            }
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tableId"></param>
        /// <param name="pkColumns"></param>
        /// <param name="pkValues"></param>
        /// <param name="columnName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ServiceResult UpdateData(string userId, Guid tableId, string[] pkColumns, string[] pkValues, string columnName, string value)
        {
            if(pkColumns.Contains(columnName))
            {
                return new ServiceResult(false, ErrorCode.DtTable_PKCannotChange, ErrorCode.String(ErrorCode.DtTable_PKCannotChange));
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);
                Entities.EDtTable eTable = dtRep.Get(p => p.Id == tableId);

                EntityRepository<Entities.EDtTableColumn> dttcRep = new EntityRepository<Entities.EDtTableColumn>(dbContext);

                Entities.EDtTableColumn eDtTableColumn = dttcRep.Get(p => p.DtTableId == tableId && p.Name == columnName);
                if(eDtTableColumn == null)
                {
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }

                StringBuilder dataIdentityBuilder = new StringBuilder();

                for (int index = 0; index < pkColumns.Length; index++)
                {
                    dataIdentityBuilder.AppendFormat("{0}={1},", pkColumns[index], pkValues[index]);
                }

                string oldValue = null;
                if (DtTableUtil.UpdateDataValueToTable(dbContext, eTable.ActualName, pkColumns, pkValues, columnName, value, out oldValue))
                {
                    dbContext.Database.ExecuteSqlCommand("exec [ETL_SP_InsertDtTableDataHistory] @Id={0}, @DtTableId={1},@DataId={2},@ColumnId={3},@NewValue={4},@Reason={5},@CreatedTime={6},@Creator={7},@OldValue={8}",
                        Guid.NewGuid(),
                        eTable.Id,
                        dataIdentityBuilder.ToString(),
                        eDtTableColumn.Id,
                        value,
                        DEF.DtTableDataUpdateReason.Adjust,
                        DateTime.Now,
                        userId,
                        oldValue);

                    return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                }
                else
                {
                    return new ServiceResult(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                }
            }
        }

        /// <summary>
        /// 获取数据表的所有修改记录
        /// </summary>
        /// <param name="tableId"></param>
        /// <returns></returns>
        public ListResult<Views.VDtTableDataHistory> GetHistories(Guid tableId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                List<Views.VDtTableDataHistory> list = dbContext.Database.SqlQuery<Views.VDtTableDataHistory>("exec [ETL_SP_GetDataTableLatestDataHistiroies] @DtTableId={0}", tableId).ToList();

                return new ListResult<Views.VDtTableDataHistory>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), list);
            }
        }
        
        public ListResult<Views.VDtTableDataHistory> GetCellHistories(Guid tableId, string[] pkColumns, string[] pkValues, string columnName)
        {
            StringBuilder dataIdentityBuilder = new StringBuilder();

            for (int index = 0; index < pkColumns.Length; index++)
            {
                dataIdentityBuilder.AppendFormat("{0}={1},", pkColumns[index], pkValues[index]);
            }

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                List<Views.VDtTableDataHistory> list = dbContext.Database.SqlQuery<Views.VDtTableDataHistory>("exec [ETL_SP_GetDataTableDataHistoryList] @DtTableId={0},@DataId={1},@ColumnName={2}", tableId, dataIdentityBuilder.ToString(), columnName).ToList();

                return new ListResult<Views.VDtTableDataHistory>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), list);
            }
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="columnSettings">name,type,length,nullable,description</param>
        /// <returns></returns>
        public ServiceResult<Entities.EDtTable> Create(string userId, string tableName, string columnSettings)
        {
            if(string.IsNullOrEmpty(columnSettings))
            {
                return new ServiceResult<Entities.EDtTable>(false, ErrorCode.DtTable_InvalidColumnSettings, ErrorCode.String(ErrorCode.DtTable_InvalidColumnSettings));
            }

            string[] columnSettingArr = columnSettings.Split(new char[] { ',' });

            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);
                EntityRepository<Entities.EDtTableColumn> dtcRep = new EntityRepository<Entities.EDtTableColumn>(dbContext);

                if( dtRep.Count(p => p.Name == tableName) > 0)
                {
                    return new ServiceResult<Entities.EDtTable>(false, ErrorCode.DtTable_NameExist, ErrorCode.String(ErrorCode.DtTable_NameExist));
                }

                DateTime now = DateTime.Now;

                bool isRawDt = true;
                Entities.EDtTable eDtTable = new Entities.EDtTable();
                eDtTable.Id = Guid.NewGuid();
                eDtTable.Name = tableName;
                eDtTable.Creator = userId;
                eDtTable.CreatedTime = now;
                eDtTable.ActualName = string.Format("ETL_DT_{0}", tableName);
                eDtTable.CacheName = string.Format("ETL_DTC_{0}", tableName);
                eDtTable.IsRawDt = isRawDt;

                dtRep.Create(eDtTable);

                List<string> dtTableColNames = new List<string>();
                List<string> dtTableColTypes = new List<string>();
                List<string> dtTableColLength = new List<string>();
                List<bool> dtTableColNullable = new List<bool>();

                for (int index = 0; index < columnSettingArr.Length; index += 5)
                {
                    dtTableColNames.Add(columnSettingArr[index]);
                    dtTableColTypes.Add(columnSettingArr[index + 1]);
                    dtTableColLength.Add(columnSettingArr[index + 2]);
                    dtTableColNullable.Add(Convert.ToBoolean(columnSettingArr[index + 3]));

                    // create table column
                    Entities.EDtTableColumn eDtColumn = new Entities.EDtTableColumn();
                    eDtColumn.Id = Guid.NewGuid();
                    eDtColumn.Name = columnSettingArr[index];
                    eDtColumn.Type = columnSettingArr[index + 1];
                    try
                    {
                        eDtColumn.Length = Convert.ToInt16(columnSettingArr[index + 2]);
                    }
                    catch (Exception ex)
                    {
                        Logger.DebugToTag(Library.LogTAG, string.Format("table:{0},转换列映射的Lenght出错，不是有效的int类型的数据", tableName));
                        eDtColumn.Length = 0;
                    }
                    eDtColumn.IsSYS = false;
                    eDtColumn.PK = false;
                    eDtColumn.Nullable = Convert.ToBoolean(columnSettingArr[index + 3]);
                    eDtColumn.Creator = userId;
                    eDtColumn.CreatedTime = now;
                    eDtColumn.DtTableId = eDtTable.Id;
                    eDtColumn.Description = columnSettingArr[index + 4];
                    dtcRep.Create(eDtColumn);
                }

                if (CPPEI.ETL.Domain.Util.DtTableUtil.CreateRawDataTable(dbContext,
                    eDtTable.ActualName,
                    eDtTable.CacheName,
                    isRawDt,
                    dtTableColNames,
                    dtTableColTypes,
                    dtTableColLength,
                    dtTableColNullable) == false)
                {
                    return new ServiceResult<Entities.EDtTable>(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                }

                try
                {
                    if (dbContext.SaveChanges() > 0)
                    {
                        return new ServiceResult<Entities.EDtTable>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), eDtTable);
                    }
                    else
                    {
                        return new ServiceResult<Entities.EDtTable>(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("映射到新数据表出错,ex:{0}", ex));
                    return new ServiceResult<Entities.EDtTable>(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        public ServiceResult UpdateDescription(Guid dataTableId, string description)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);

                Entities.EDtTable eDtTable = dtRep.Get(p => p.Id == dataTableId);
                if (eDtTable == null)
                {
                    return new ServiceResult(false, ErrorCode.COM_OBJNotExist, ErrorCode.String(ErrorCode.COM_OBJNotExist));
                }

                eDtTable.Description = description;
                dtRep.Update(eDtTable);

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError));
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("更新数据表:{0}的备注,出错,ex:{1}", dataTableId, ex));
                    return new ServiceResult(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }
            }
        }

        #region third party table


        /// <summary>
        /// 获取第三方的数据表，不是通过系统创建的
        /// </summary>
        /// <returns></returns>
        public PagedList<Data.ThirdPartyTable> GetThirdPartyTables(string filter, int start, int limit)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                List<CPPEI.ETL.Infrastructure.SQLServer.Table> list = CPPEI.ETL.Infrastructure.SQLServer.SQLServer2008.GetTables(dbContext.Database.Connection as System.Data.SqlClient.SqlConnection, null);

                List<Data.ThirdPartyTable> tables = new List<Data.ThirdPartyTable>();

                int total = 0;
                if(!string.IsNullOrEmpty(filter))
                {
                    for (int index = 0; index < list.Count; index++)
                    {
                        if (!list[index].Name.StartsWith("ETL_") && list[index].Name.Contains(filter))
                        {
                            if (total >= start && total < limit)
                            {
                                Data.ThirdPartyTable table = new Data.ThirdPartyTable();
                                table.Id = list[index].Id;
                                table.Name = list[index].Name;
                                tables.Add(table);
                            }
                            total++;
                        }
                    }
                }
                else
                {
                    for (int index = 0; index < list.Count; index++)
                    {
                        if (!list[index].Name.StartsWith("ETL_"))
                        {
                            if (total >= start && total < limit)
                            {
                                Data.ThirdPartyTable table = new Data.ThirdPartyTable();
                                table.Id = list[index].Id;
                                table.Name = list[index].Name;
                                tables.Add(table);
                            }
                            total++;
                        }
                    }
                }

                return new PagedList<Data.ThirdPartyTable>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), start, limit, total, tables);
            }
        }

        /// <summary>
        /// 获取数据表的列信息
        /// </summary>
        /// <param name="tableId"></param>
        /// <returns></returns>
        public ListResult<Data.ThirdPartyTableColumn> GetThirdPartyColumns(int tableId)
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                List<CPPEI.ETL.Infrastructure.SQLServer.Column> list = CPPEI.ETL.Infrastructure.SQLServer.SQLServer2008.GetColumns(dbContext.Database.Connection as System.Data.SqlClient.SqlConnection, tableId);


                List<Data.ThirdPartyTableColumn> columns = new List<Data.ThirdPartyTableColumn>();
                for (int index = 0; index < list.Count; index++)
                {
                    Data.ThirdPartyTableColumn column = new Data.ThirdPartyTableColumn();
                    column.IsNullable = list[index].IsNullable;
                    column.Index = list[index].Index;
                    column.Length = list[index].Length;
                    column.Name = list[index].Name;
                    column.PK = list[index].PK;
                    column.Type = list[index].Type;

                    columns.Add(column);
                }

                return new ListResult<Data.ThirdPartyTableColumn>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), columns);
            }
        }

        /// <summary>
        /// 将第三方数据表转成系统内的数据表
        /// </summary>
        /// <param name="tableId"></param>
        /// <returns></returns>
        public ServiceResult<Entities.EDtTable> ConvertToDtTable(int tableId)
        {
            using(EtlDbContext dbContext = new EtlDbContext())
            {
                CPPEI.ETL.Infrastructure.SQLServer.Table table = CPPEI.ETL.Infrastructure.SQLServer.SQLServer2008.GetTable(dbContext.Database.Connection as System.Data.SqlClient.SqlConnection, tableId);
                List<CPPEI.ETL.Infrastructure.SQLServer.Column> columns = CPPEI.ETL.Infrastructure.SQLServer.SQLServer2008.GetColumns(dbContext.Database.Connection as System.Data.SqlClient.SqlConnection, tableId);

                EntityRepository<Entities.EDtTable> dtRep = new EntityRepository<Entities.EDtTable>(dbContext);
                EntityRepository<Entities.EDtTableColumn> dtcRep = new EntityRepository<Entities.EDtTableColumn>(dbContext);

                if(dtRep.Count(p=>p.Name == table.Name) > 0)
                {
                    return new ServiceResult<Entities.EDtTable>(false, ErrorCode.DtTable_NameExist, ErrorCode.String(ErrorCode.DtTable_NameExist));
                }

                string cacheTableName = string.Format("ETL_EDTC_{0}", table.Name);
                // 创建数据表信息
                Entities.EDtTable eDtTable = new Entities.EDtTable();
                eDtTable.Id = Guid.NewGuid();
                eDtTable.ActualName = table.Name;
                eDtTable.CacheName = cacheTableName;
                eDtTable.CreatedTime = DateTime.Now;
                eDtTable.Creator = "system";
                eDtTable.Description = table.Name;
                eDtTable.IsRawDt = false;
                eDtTable.Name = table.Name;
                dtRep.Create(eDtTable);
                
                List<string> dtTableColNames = new List<string>();
                List<string> dtTableColTypes = new List<string>();
                List<string> dtTableColLength = new List<string>();
                List<bool> dtTableColNullable = new List<bool>();

                for (int index = 0; index < columns.Count; index++)
			    {
                    dtTableColNames.Add(columns[index].Name);
                    dtTableColTypes.Add(columns[index].Type);
                    dtTableColLength.Add(columns[index].Length.ToString());
                    dtTableColNullable.Add(columns[index].IsNullable);

                    Entities.EDtTableColumn eDtColumn = new Entities.EDtTableColumn();
                    eDtColumn.CreatedTime = DateTime.Now;
                    eDtColumn.Creator = "system";
                    eDtColumn.Description = columns[index].Name;
                    eDtColumn.DtTableId = eDtTable.Id;
                    eDtColumn.Id = Guid.NewGuid();
                    eDtColumn.IsSYS = false;
                    eDtColumn.PK = columns[index].PK;
                    eDtColumn.Length = columns[index].Length;
                    eDtColumn.Name = columns[index].Name;
                    eDtColumn.Nullable = columns[index].IsNullable;
                    eDtColumn.Type = columns[index].Type;
                    eDtColumn.Index = index;
                    dtcRep.Create(eDtColumn);
                }

                try
                {
                    dbContext.SaveChanges();

                    // 创建一个缓存数据表
                    if (CPPEI.ETL.Domain.Util.DtTableUtil.CreateCacheDataTable(dbContext,
                        cacheTableName,
                        dtTableColNames,
                        dtTableColTypes,
                        dtTableColLength,
                        dtTableColNullable) == false)
                    {
                        return new ServiceResult<Entities.EDtTable>(false, ErrorCode.COM_DBError, ErrorCode.String(ErrorCode.COM_DBError));
                    }

                    return new ServiceResult<Entities.EDtTable>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), eDtTable);
                }
                catch(Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("转换数据表:{0}为内部数据表出错,ex:{1}", table.Name, ex));

                    return new ServiceResult<Entities.EDtTable>(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception), null);
                }
            }
        }
        #endregion
    }
}
